<template>
    <div class='colletc-container'>
        <div class="main">
            <div class="main-head">
                <ul>
                    <li @click="() => { active = 0 }"
                        :class="active == 0 ? 'mh-padding all-baby border-bottom' : 'mh-padding all-baby'">
                        <div>
                            全部宝贝{{ collectList.length }}
                        </div>
                    </li>

                    <li @click="() => { active = 1 }"
                        :class="active == 1 ? 'mh-padding lose border-bottom' : 'mh-padding down'">
                        <div>
                            降价{{ cutPrice }}
                        </div>
                    </li>

                    <li @click="() => { active = 2 }"
                        :class="active == 2 ? 'mh-padding lose border-bottom' : 'mh-padding lose'">
                        <div>
                            失效{{ lose }}
                        </div>
                    </li>
                    <li class="mh-right">
                        <!-- <div>  -->
                        <div class="delete-co" v-if="allOption" @click="batchDelete()">
                            <span>删除选中</span>
                        </div>
                        <div v-if="allOption">
                            <el-checkbox class="all-in" :isIndeterminate="isIndeterminate" v-model="checkAll"
                                @change="handleCheckAllChange">全选</el-checkbox>
                        </div>
                        <div class="batch-manage" @click="batchOption()">
                            批量管理
                        </div>
                        <!-- </div> -->
                    </li>
                    <!-- //搜索 -->
                    <li class="mh-right">
                        <!-- <div class="collect-search">
                            <input type="text" >
                            <span><i class="el-icon-search"></i></span>
                        </div> -->
                    </li>
                </ul>
            </div>
            <div class="main-body" v-if="show">
                <div class="body-item" v-for="collect in collectList" v-if="checkShow(collect)">
                    <div class="spuimg">

                        <img :src="collect.spuImg" alt="" @click="goDetail(collect.spuId)">
                        <div class="option" @click="deleteCollect(collect.id)">
                            <i class="el-icon-delete-solid"></i>
                        </div>

                        <div class="change" :style="allOption ? 'display: block;' : ''">
                            <el-checkbox-group v-model="checkedProduct" @change="handleCheckedCitiesChange">
                                <el-checkbox :label="collect.id" :key="collect.id">{{ null }}</el-checkbox>
                            </el-checkbox-group>

                        </div>

                        <div class="button-option">
                            <li><span @click="goMemberIndex(collect.spuId)">商家首页</span></li> |
                            <li><span @click="findLike(collect.spuId)">找相似</span></li>
                        </div>
                    </div>
                    <div class="spudetail" @click="goDetail(collect.spuId)">
                        <span v-html="collect.spuName"></span>
                    </div>
                    <div class="spuprice" v-if="!(getPrice(collect.spuId) == null)">
                        <!-- 当前价格 -->
                        <span class="now-price">￥{{ getPrice(collect.spuId) }}</span>
                        <!-- 收藏时价格 -->
                        <span class="collect-price" v-if="getPrice(collect.spuId) < collect.beforePrice">￥{{
                            collect.beforePrice }}</span>
                    </div>
                    <div class="other-container" v-if="getPrice(collect.spuId) == null">
                        <span><i class="el-icon-error"></i> 宝贝已失效了</span>
                    </div>
                </div>
                <div
                    v-if="active == 0 && collectList.length == 0 || active == 1 && cutPrice == 0 || active == 2 && lose == 0">
                    <el-empty :image-size="400"></el-empty>
                </div>
            </div>

        </div>
    </div>
</template>

<script>

const productOptions = [];
import getUUID from '../../utils/uuid';

export default {
    name: 'collectTemplate',
    data() {
        return {

            checkAll: false,   // 是否选中全部
            checkedProduct: [],    // 默认选中的，选中的
            products: productOptions,    // 选中的数据，里面是收藏夹的id集合
            isIndeterminate: false,  // 控制全部选中的样式

            active: 0,   // 0-全部宝贝  1-降价的  2-失效的
            memberVo: [],   // 用户信息
            collectList: [],   // 收藏夹列表
            spuIds: [],    // 商品id
            prices: new Map(),    // 每个收藏夹对应的最新价格
            show: false,     // 数据加载后show显示为true
            allOption: false,    // 操作所有的标识，表示是否打开

            cutPrice: 0,   // 降价的有多少个
            lose: 0,  // 失效的有多少个
        };
    },

    components: {
    },

    methods: {

        // 找相似
        async findLike(spuId) {
            let keyword = null;
            await this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/spuinfo/getSpuInfoVo?spuId=${spuId}`),
                method: 'post',
            }).then(({ data }) => {
                if (data.code == 200) {
                    let temp = JSON.parse(data.data)
                    if (temp.brand != null && temp.brand != '') {
                        keyword = temp.brand
                    } else if (temp.category != null && temp.category != '') {
                        keyword = temp.category
                    } else {
                        keyword = temp.spuName
                    }
                }
            })
            console.log(keyword)
            this.$router.push({
                path: "/member/search",
                query: {
                    search: keyword
                }
            })
        },


        // 前往用户首页
        async goMemberIndex(spuId) {
            // 通过spuId查找
            let productInfo = null
            await this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/spuinfo/getMemberIds?spuIds=${[spuId]}`),
                method: 'post',
            }).then(({ data }) => {
                if (data.code == 200) {
                    productInfo = JSON.parse(data.data)
                }
            })

            this.$router.push({
                path: '/member/othermember',
                query: {
                    memberId: productInfo.memberIds[0],
                    params: getUUID()
                }
            })
        },


        /**
         * 筛选
         * @param {*} collect 
         */
        checkShow(collect) {
            if (this.active == 0) {
                return true;
            } else if (this.active == 1) {
                let beforePrice = collect.beforePrice
                let nowPrice = this.prices.get(collect.spuId);
                if (beforePrice > nowPrice && nowPrice != null) {
                    return true;
                } else {
                    return false;
                }
            } else if (this.active == 2) {
                if (this.prices.get(collect.spuId) == null) {
                    return true;
                } else {
                    return false;
                }
            }
        },


        /**
         * 批量操作
         */
        batchOption() {
            this.allOption = !this.allOption
            // 如果当前的批量操作为false，那么将选中的全部都归空
            if (!this.allOption) {
                this.checkedProduct = []
                this.isIndeterminate = false
            }
        },


        /**
         * 批量删除
         */
        batchDelete() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-member/shitoumember/membercollectspu/deleteBatchCollect?memberId=${this.memberVo.id}&idS=${this.checkedProduct}`),
                method: 'post',
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '批量删除收藏商品成功'
                    })
                    this.show = false
                    this.getAllCollect()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 删除单个收藏
         * @param {*} id 
         */
        deleteCollect(id) {
            this.$http({
                url: this.$http.adornUrl(`/shitou-member/shitoumember/membercollectspu/deleteCollect?memberId=${this.memberVo.id}&id=${id}`),
                method: 'post',
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '删除收藏商品成功'
                    })
                    this.show = false
                    this.getAllCollect()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 商品id，前往商品详情页面
         * @param {*} spuId 
         * @param {*} sale
         */
        goDetail(spuId) {
            if (this.prices.get(spuId) == null) {
                this.$message({
                    type: 'warning',
                    message: '商品已下架或售罄'
                })
                return;
            }
            this.$router.push({
                path: '/product/productDetail',
                query: { spuId: spuId, search: getUUID() }
            })
        },


        /**
         * 选中全部
         * @param {*} val 判断是否全选的依据
         */
        handleCheckAllChange(val) {
            this.checkedProduct = val ? productOptions : [];
            this.isIndeterminate = false;
        },


        /**
         * 选中单个时，判断是否已经全部选中
         * @param {*} value 当前chebox节点的值
         */
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.products.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.products.length;
        },


        /**
         * 获得价格
         * @param {*} spuId 
         */
        getPrice(spuId) {
            return this.prices.get(spuId)
        },


        /**
         * 获取单个商品信息,返回价格
         * @param {*} spuId 
         */
        async getSpuInfo() {

            await this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/spuinfo/getProductBySpuIds?spuIds=${this.spuIds}`),
                method: 'post',
            }).then(({ data }) => {
                if (data.code == 200 && data.data != null) {
                    data.data.forEach((item) => {
                        this.prices.set(item.spuId, item.spuPrice)
                    })
                    // 计算商品失效的件数  计算商品降价件数
                    for (let i = 0; i < this.collectList.length; i++) {
                        let collect = this.collectList[i]
                        let beforePrice = collect.beforePrice
                        let nowPrice = this.prices.get(collect.spuId);

                        if (nowPrice == null) {
                            this.lose++;
                            continue;
                        }
                        if (beforePrice > nowPrice) {
                            this.cutPrice++;
                        }
                    }
                    // 获取数据后在展示
                    this.show = true;
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 获取收藏品
         */
        async getAllCollect() {

            await this.$http({
                url: this.$http.adornUrl(`/shitou-member/shitoumember/membercollectspu/getMemberCollect?memberId=${this.memberVo.id}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.collectList = data.data
                    this.getSpuIds()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 获取所有的收藏商品id
         */
        getSpuIds() {
            let index = -1;
            this.collectList.forEach((item) => {
                this.spuIds[++index] = item.spuId
                this.prices.set(item.spuId, null)
                productOptions.push(item.id)
            })
            this.getSpuInfo()
        }

    },

    async beforeMount() {
        let member = await this.$memberInfo()
        if (member != null) {
            this.memberVo = member
            this.getAllCollect()
        }
    }
}
</script>

<style scoped>
@import url("../../utils/css/colletc.css");
</style>